<template>
  <div class="nursing-record-page" style="margin: 100px;">
    <!-- 顶部信息 -->
    <div class="page-header">
      <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
      <h2>护理记录信息</h2>
    </div>
    <div class="patient-info">
      <div>
        姓名：{{ patientInfo.name }}　年龄：{{ patientInfo.age }}　性别：{{ patientInfo.sex }}　
        科室：{{ patientInfo.officeCode }}　床号：{{ patientInfo.bedCode }}　
        　住院号：{{ patientInfo.wardCode }} 诊断：{{ patientInfo.diagnosis }}
      </div>
    </div>

    <!-- 护理记录表单 -->
    <el-form v-loading="loading" ref="ruleFormRef" :model="form" :rules="rules" label-width="80px" class="nursing-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="呼吸" prop="breathe">
            <el-input v-model="form.breathe" suffix="次/分" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="体温" prop="temperature">
            <el-input v-model="form.temperature" suffix="℃" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="脉率" prop="rate">
            <el-input v-model="form.rate" suffix="次/分" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="血氧" prop="oximetry">
            <el-input v-model="form.oximetry" suffix="ml" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="心率" prop="heartRate">
            <el-input v-model="form.heartRate" suffix="次/分" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="血压高" prop="maxBP">
            <el-input v-model="form.maxBP" suffix="ml" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="血压低" prop="minBP">
            <el-input v-model="form.minBP" suffix="ml" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="护理措施及效果" prop="measures">
        <el-input type="textarea" v-model="form.measures" :rows="3" placeholder="请输入" />
      </el-form-item>


      <el-form-item label="签名" style="margin-bottom: 18px;">
        <div style="display: flex; flex-direction: column;">
          <canvas ref="signCanvas" width="300" height="80"
            style="border:1px solid #ccc; border-radius: 4px; background: #fff;"></canvas>
          <div style="margin-top: 8px;">
            <el-button size="small" @click="clearSignature">清除</el-button>
            <el-button size="small" @click="previewSignature" style="margin-left: 8px;">浏览</el-button>
          </div>
        </div>
      </el-form-item>

      <el-form-item style="text-align: center;">
        <el-button type="primary" @click="onSubmit" style="width: 100px;">保存</el-button>
        <el-button @click="onReset" style="width: 100px; margin-left: 30px;">重置</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="previewVisible" title="签名预览" width="340px" :close-on-click-modal="true">
      <div style="text-align:center;">
        <img :src="previewImg" alt="签名预览" style="max-width:300px;max-height:80px;border:1px solid #eee;" />
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import http from '@/api/http.js';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();

// 加载状态
const loading = ref(false);
// 患者信息
const patientInfo = reactive({
  name: '',
  age: '',
  sex: '',
  officeCode: '',
  bedCode: '',
  wardCode: '',
  diagnosis: ''
});

onMounted(() => {
  // 从路由参数获取患者信息
  const patientCode = route.query.patientCode as string;
  // 直接从路由参数填充患者信息
  patientInfo.name = route.query.name as string || '';
  patientInfo.sex = route.query.sex === '1' ? '男' : (route.query.sex === '2' ? '女' : '');
  patientInfo.age = route.query.age as string || '';
  patientInfo.officeCode = route.query.officeCode as string || '';
  patientInfo.bedCode = route.query.bedCode as string || '';
  patientInfo.wardCode = route.query.wardCode as string || '';
  patientInfo.diagnosis = route.query.diagnosis as string || '';

  // 如果有患者编号，则获取患者详细信息


  if (patientCode) {
    form.patientCode = patientCode;
    loading.value = true;
    // 获取患者详细信息
    http.get(`/api/PatientReCordController/GetPatientInfo?PatientCode=${patientCode}`).then(res => {
      if (res) {
        Object.assign(patientInfo, res);

      } else {
        ElMessage.warning('未找到患者信息');
      }
    }).catch(err => {
      console.error('获取患者信息失败:', err);
      ElMessage.error('获取患者信息失败');
    }).finally(() => {
      loading.value = false;
    });
  } else {
    ElMessage.warning('缺少必要的患者信息参数');
  }
});

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  breathe: [
    { required: true, message: '请输入呼吸', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  temperature: [
    { required: true, message: '请输入体温', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的体温格式', trigger: 'blur' }
  ],
  rate: [
    { required: true, message: '请输入脉率', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  oximetry: [
    { required: true, message: '请输入血氧', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  heartRate: [
    { required: true, message: '请输入心率', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  maxBP: [
    { required: true, message: '请输入血压高', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  minBP: [
    { required: true, message: '请输入血压低', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
  ],
  measures: [
    { required: true, message: '请输入护理措施及效果', trigger: 'blur' },
    { min: 10, message: '护理措施及效果不能少于10个字符', trigger: 'blur' }
  ],
  signUrl: [{ required: true, message: '请签名', trigger: 'change' }],
})

const form: any = reactive({
  patientCode: '',
  breathe: '',
  temperature: '',
  rate: '',
  oximetry: '',
  heartRate: '',
  maxBP: '',
  minBP: '',
  measures: '',
  signUrl: '',
})


// Canvas 相关变量
const signCanvas = ref<HTMLCanvasElement | null>(null);
let ctx: CanvasRenderingContext2D | null = null;
let drawing = false;

// Canvas 初始化和事件绑定
onMounted(() => {
  if (!signCanvas.value) return;
  ctx = signCanvas.value.getContext('2d');
  if (!ctx) return;

  ctx.strokeStyle = '#000';
  ctx.lineWidth = 2;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';

  // 事件监听器
  const canvas = signCanvas.value;
  canvas.addEventListener('mousedown', startDrawing as EventListener);
  canvas.addEventListener('mousemove', draw as EventListener);
  canvas.addEventListener('mouseup', stopDrawing);
  canvas.addEventListener('mouseout', stopDrawing);
  canvas.addEventListener('touchstart', startTouch as EventListener);
  canvas.addEventListener('touchmove', moveTouch as EventListener);
  canvas.addEventListener('touchend', stopDrawing);
});



// 绘图相关函数
function startDrawing(e: MouseEvent) {
  if (!ctx || !signCanvas.value) return;
  drawing = true;
  const rect = signCanvas.value.getBoundingClientRect();
  ctx.beginPath();
  ctx.moveTo(e.clientX - rect.left, e.clientY - rect.top);
}

function draw(e: MouseEvent) {
  if (!drawing || !ctx || !signCanvas.value) return;
  const rect = signCanvas.value.getBoundingClientRect();
  ctx.lineTo(e.clientX - rect.left, e.clientY - rect.top);
  ctx.stroke();
}

function stopDrawing() {
  drawing = false;
}

// 触摸事件处理
function startTouch(e: TouchEvent) {
  if (!ctx || !signCanvas.value) return;
  e.preventDefault();
  drawing = true;
  const rect = signCanvas.value.getBoundingClientRect();
  const touch = e.touches[0];
  ctx.beginPath();
  ctx.moveTo(touch.clientX - rect.left, touch.clientY - rect.top);
}

function moveTouch(e: TouchEvent) {
  if (!drawing || !ctx || !signCanvas.value) return;
  e.preventDefault();
  const rect = signCanvas.value.getBoundingClientRect();
  const touch = e.touches[0];
  ctx.lineTo(touch.clientX - rect.left, touch.clientY - rect.top);
  ctx.stroke();
}


// 工具函数
function clearSignature() {
  if (!ctx || !signCanvas.value) return;
  ctx.clearRect(0, 0, signCanvas.value.width, signCanvas.value.height);
  form.signUrl = '';
}

const previewVisible = ref(false)
const previewImg = ref('')

function previewSignature() {
  if (!signCanvas.value) {
    ElMessage.warning('请先签名');
    return;
  }
  // 判断canvas是否有内容
  const imageData = ctx?.getImageData(0, 0, signCanvas.value.width, signCanvas.value.height).data;
  if (!imageData || imageData.every(pixel => pixel === 0 || pixel === 255)) {
    ElMessage.warning('签名不能为空');
    return;
  }
  previewImg.value = signCanvas.value.toDataURL('image/png');
  previewVisible.value = true;
}

// 提交处理
const onSubmit = async () => {
  if (!signCanvas.value) {
    ElMessage.warning('请先签名');
    return;
  }

  const imageData = ctx?.getImageData(0, 0, signCanvas.value.width, signCanvas.value.height).data;
  if (!imageData || imageData.every(pixel => pixel === 0 || pixel === 255)) {
    ElMessage.warning('签名不能为空，请签名后再提交');
    return;
  }

  try {
    const signatureDataUrl = signCanvas.value.toDataURL('image/png');
    const base64Data = signatureDataUrl.split(',')[1];

    // 上传签名图片
    const newimgurl = await http.post('/api/InAssessController/UpdateImg', base64Data);


    form.signUrl = newimgurl;

    // 提交表单
    await http.post('/api/PatientReCordController/AddPatientReCord', form);

    ElMessage.success('保存成功');

    // 构建新记录对象
    const newRecord = {
      patientCode: form.patientCode,
      recordTime: form.recordTime,
      temperature: form.temperature,
      heartRate: form.heartRate,
      breathe: form.breathe,
      bp: `${form.maxBP}/${form.minBP}`,
      oximetry: form.oximetry,
      measures: form.measures,
      signUrl: form.signUrl,

    };

    router.push({
      path: '/PatientReCordShow',
      query: {
        sex: patientInfo.sex,
        name: patientInfo.name,
        age: patientInfo.age,
        officeCode: patientInfo.officeCode,
        bedCode: patientInfo.bedCode,
        wardCode: patientInfo.wardCode,
        diagnosis: patientInfo.diagnosis,
        recordTime: form.recordTime,


      }
    });
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败，请重试');
  }
};








// 添加返回按钮
const goBack = () => {
  router.back();
}

function onReset() {
  // 清空表单字段
  for (const key in form) {
    if (Object.prototype.hasOwnProperty.call(form, key)) {
      form[key] = '';
    }
  }
  // 清空签名
  clearSignature();
  // 如果有表单ref，重置校验
  ruleFormRef.value?.clearValidate();
}

</script>

<style scoped>
.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.patient-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  color: #606266;
}

.nursing-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.signature-box {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background-color: #fff;
}

.signature-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.signature-tip {
  color: #606266;
  font-size: 14px;
}

.signature-canvas {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  cursor: crosshair;
}

.signature-footer {
  margin-top: 10px;
  text-align: center;
}

.signature-warning {
  color: #f56c6c;
  font-size: 12px;
}

.signature-buttons {
  display: flex;
  gap: 10px;
}

.signature-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  object-fit: contain;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>